package com.task.controller.annotation.impl;

import com.task.controller.annotation.*;
import com.task.controller.util.ReflectionsUtil;
import ohos.app.Context;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;

public class FunctionImpl {

    public static void initFunction(Context context) throws InvocationTargetException, IllegalAccessException, InstantiationException {
        Set<Class<?>> classes = ReflectionsUtil.getClassByAnnotationClass(Function.class);
        if (classes == null) {
            return;
        }
        for (Class<?> aClass : classes) {
            Constructor<?>[] constructors = aClass.getDeclaredConstructors();
            for (Constructor<?> constructor : constructors) {
                Class<?>[] types = constructor.getParameterTypes();
                Object instance = null;
                if (types.length == 1) {
                    if (types[0].isInstance(context)) {
                        instance = constructor.newInstance(context);
                    }
                } else if (types.length == 0) {
                    instance = constructor.newInstance();
                }
                TaskImpl.initTask(instance);
            }
        }
    }
}
